<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.6" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.6">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.6">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.6">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.6" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.0.6',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="Hexo, NexT" />


<meta name="description" content="python基础回顾演变先有类，再出现对象，对象生存在内存里; 理论1、一切都皆为对象，一切皆为对象的引用。2、只有对名字（变量名-变量）赋值的时候，才会变更引用关系。 变量1、变量是用一个变量名表示，变量名必须是大小写英文、数字和下划线（_）的组合，且不能用数字开头。2、变量是在内存中开辟的一个空间，实际表示是name(字符串):name.ref(内存地址)。3、我们通常将变量名代表变量，变量值">
<meta property="og:type" content="article">
<meta property="og:title" content="python基础回顾（一）">
<meta property="og:url" content="http://7ht.gitee.io/2018/03/27/python基础回顾（一）/index.html">
<meta property="og:site_name" content="HonTu&#39;s Notes">
<meta property="og:description" content="python基础回顾演变先有类，再出现对象，对象生存在内存里; 理论1、一切都皆为对象，一切皆为对象的引用。2、只有对名字（变量名-变量）赋值的时候，才会变更引用关系。 变量1、变量是用一个变量名表示，变量名必须是大小写英文、数字和下划线（_）的组合，且不能用数字开头。2、变量是在内存中开辟的一个空间，实际表示是name(字符串):name.ref(内存地址)。3、我们通常将变量名代表变量，变量值">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-03-28T05:01:18.255Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="python基础回顾（一）">
<meta name="twitter:description" content="python基础回顾演变先有类，再出现对象，对象生存在内存里; 理论1、一切都皆为对象，一切皆为对象的引用。2、只有对名字（变量名-变量）赋值的时候，才会变更引用关系。 变量1、变量是用一个变量名表示，变量名必须是大小写英文、数字和下划线（_）的组合，且不能用数字开头。2、变量是在内存中开辟的一个空间，实际表示是name(字符串):name.ref(内存地址)。3、我们通常将变量名代表变量，变量值">






  <link rel="canonical" href="http://7ht.gitee.io/2018/03/27/python基础回顾（一）/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>python基础回顾（一） | HonTu's Notes</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> 

<div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HonTu's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一小瓶</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        
          
  <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
</li>

      
        
        
          
  <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
</li>

      

      
    </ul>
  

  

  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://7ht.gitee.io/2018/03/27/python基础回顾（一）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Q.hongtao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/head_cat.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HonTu's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">python基础回顾（一）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-27T23:12:59+08:00">2018-03-27</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="python基础回顾"><a href="#python基础回顾" class="headerlink" title="python基础回顾"></a>python基础回顾</h1><h3 id="演变"><a href="#演变" class="headerlink" title="演变"></a>演变</h3><p>先有类，再出现对象，对象生存在内存里;</p>
<h3 id="理论"><a href="#理论" class="headerlink" title="理论"></a>理论</h3><p>1、一切都皆为对象，一切皆为对象的引用。<br>2、只有对名字（变量名-变量）赋值的时候，才会变更引用关系。</p>
<h3 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h3><p>1、变量是用一个变量名表示，变量名必须是大小写英文、数字和下划线（_）的组合，且不能用数字开头。<br>2、变量是在内存中开辟的一个空间，实际表示是name(字符串):name.ref(内存地址)。<br>3、我们通常将变量名代表变量，变量值代表关联对象。</p>
<h3 id="类"><a href="#类" class="headerlink" title="类"></a>类</h3><p>1、类就是类型：object是祖先类型。<br>2、类型对象是自动生成的，有且仅有一个类型对象实例。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">int、type(1)</span><br><span class="line">&gt;&gt;&gt; type(1) is int</span><br><span class="line">&gt;&gt;&gt; True</span><br></pre></td></tr></table></figure></p>
<h3 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h3><p>1、对象：是类的实例。<br>2、存活的实例对象都有唯一的id。<br>3、每个实例对象都持有所属类型的指针。<br>4、在内存中的标准头，包括引用计数cnt、类型type、其他等。</p>
<h3 id="基础数据（对象）类型："><a href="#基础数据（对象）类型：" class="headerlink" title="基础数据（对象）类型："></a>基础数据（对象）类型：</h3><p>1、不可变数据（对象）类型：string、tuple、numbers（int、float）<br>2、可变数据（对象）类型：list、dict</p>
<h3 id="名字空间-namespace"><a href="#名字空间-namespace" class="headerlink" title="名字空间(namespace)"></a>名字空间(namespace)</h3><p><strong>是从名称到对象的映射。</strong><br><strong>局部名字空间：从Fast区域按需延迟复制的，静态作用域。</strong><br><strong>全局名字空间：模块直接用dict实现的，没有使用类似Fast的机制。</strong><br>1、名字（变量名）、目标对象。</p>
<ul>
<li>将变量（名字）与对象（内存里的）关联起来的容器。</li>
<li>名字空间默认使用字典（dict）的数据结构。</li>
</ul>
<p>2、名字（变量名）的引用必须跟目标对象的引用关联起来。</p>
<ul>
<li>简单理解：变量名（字符串）的引用关联了目标对象的引用。</li>
<li>名字空间里实质上是存在{name.ref:obj.ref}的关系。可以通过id(name),看到obj.ref。</li>
</ul>
<p>3、名字（变量名）关联目标对象的引用关联表就存在于名字空间这个容器。</p>
<ul>
<li>简单理解：变量名（字符串）关联了目标对象的数据结构（字典)</li>
<li>名字空间里我们看到的是{name:obj}；</li>
<li>我们这里只考虑name(字符串):obj(目标对象)，不考虑深层次的ref；</li>
</ul>
<p>4、根据作用域的不同，分为全局名字空间和当前（局部）名字空间。—这里的当前更合适一些，当前是属于局部的；</p>
<h3 id="作用域"><a href="#作用域" class="headerlink" title="作用域"></a>作用域</h3><p><strong>Python 程序中可以直接访问一个命名空间的代码区域。</strong></p>
<h4 id="理论-1"><a href="#理论-1" class="headerlink" title="理论"></a>理论</h4><p>1）根据可变对象和不可变对象;<br>2）根据只有赋值的时候,才会便能引用关系;<br>3）同一作用域内，名字总属于单一名字空间，不会因其执行顺序将其引用到不同名字空间。<br>4）默认形参存储在函数对象的<strong>defaults</strong>里。<br>5）<strong>内存空间：简单划分Fast(局部变量)和DEREF（外层嵌套，闭包）。</strong></p>
<h4 id="局部作用域里的变量—使用dis-dis模块反汇编查看作用域"><a href="#局部作用域里的变量—使用dis-dis模块反汇编查看作用域" class="headerlink" title="局部作用域里的变量—使用dis.dis模块反汇编查看作用域"></a>局部作用域里的变量—使用dis.dis模块反汇编查看作用域</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">T1 = &quot;1&quot; #不可变对象</span><br><span class="line">T2 = []  #可变对象</span><br><span class="line">###############局部环境读取##################</span><br><span class="line">def change_string():</span><br><span class="line">    print(T1) # 读取了全局变量T1 ,按照LEGB的顺序</span><br><span class="line"></span><br><span class="line">###############局部环境创建##################</span><br><span class="line">def change_string():</span><br><span class="line">    T1 = &quot;dsd&quot; # 创建了局部变量T1 ,创建正常</span><br><span class="line"></span><br><span class="line">###############局部环境读取，创建##################</span><br><span class="line">def change_string():</span><br><span class="line">    print(T1)  # 报错  ---------局部环境读取</span><br><span class="line">               # 名字只属于一个名字空间，作用域解析根据LEGB就近原则，只属于当前局部作用域（局部名字空间）;</span><br><span class="line">               # 因此，出现歧义，报错UnboundLocalError</span><br><span class="line">               # 解决方法 可以把T1 使用global 声明为全局</span><br><span class="line">    T1 = &quot;111&quot; # 赋值  ----------局部环境读取</span><br></pre></td></tr></table></figure>
<p>在一个作用域里面给一个变量赋值的时候，Python自动认为这个变量是这个作用域的本地变量，并屏蔽作用域外的同名的变量;</p>
<h4 id="函数的参数"><a href="#函数的参数" class="headerlink" title="函数的参数"></a>函数的参数</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">###############默认形参##################</span><br><span class="line">def change_list(a=[]):</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    函数生成时，a的引用默认指向change_list的属性__defaults__,通过类的属性实现记录历史状态；</span><br><span class="line">    函数被调用时，如果传入参数，则a的引用指向传入的参数，发生引用变更；</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    print(&quot;初始：&#123;&#125;&quot;.format(a))</span><br><span class="line">    a.append(&quot;5&quot;)</span><br><span class="line">    a.append(&quot;6&quot;)</span><br><span class="line">    a = []  # 赋值发生a的引用变更</span><br><span class="line">    print(&quot;然后：&#123;&#125;&quot;.format(a))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">if __name__ == &quot;__main__&quot;:</span><br><span class="line">    print(change_list.__defaults__) # ([],)</span><br><span class="line">    change_list() # 初始：[]  然后：[]</span><br><span class="line">    change_list() # 初始：[&apos;5&apos;, &apos;6&apos;] 然后：[]</span><br><span class="line">    print(change_list.__defaults__) # ([&apos;5&apos;, &apos;6&apos;, &apos;5&apos;, &apos;6&apos;],)</span><br></pre></td></tr></table></figure>
<p>函数传入参数：意味着在函数的作用域内  创建了个局部变量，发生引用变更；<br>函数生成时，形参名字（变量）的引用默认指向函数的<strong>defaults</strong>属性；<br>函数被调用时，若传入参数，则形参名字的引用指向新传入的参数，若无，仍指向<strong>defaults</strong>；<br>函数每次调用，实际上是在新的局部作用域里，重新生成新的变量；</p>
<h3 id="引用、浅copy、深copy"><a href="#引用、浅copy、深copy" class="headerlink" title="引用、浅copy、深copy"></a>引用、浅copy、深copy</h3><h4 id="理论-2"><a href="#理论-2" class="headerlink" title="理论"></a>理论</h4><p>1）根据可变对象和不可变对象;<br>2）根据只有赋值的时候,才会便能引用关系;</p>
<h4 id="引用：指向同一个对象"><a href="#引用：指向同一个对象" class="headerlink" title="引用：指向同一个对象"></a>引用：指向同一个对象</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a=5 b=a 就是引用，a、b指向同一个对象;</span><br></pre></td></tr></table></figure>
<h4 id="浅copy：只复制对象内部的已有的名字引用"><a href="#浅copy：只复制对象内部的已有的名字引用" class="headerlink" title="浅copy：只复制对象内部的已有的名字引用;"></a>浅copy：只复制对象内部的已有的名字引用;</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">a=[&quot;1&quot;,2,[1,2,3]]</span><br><span class="line">b=a.copy()  # 只复制a已有对象的名字引用；就是b[0]指向a[0] ,b[1]指向a[1] ,b[2]指向a[2]</span><br><span class="line"></span><br><span class="line">########更改已有的名字引用,可变数据类型#########</span><br><span class="line">b[2].append(4) # b[2]更改后a[2]会保持一致；---b[2]是列表(可变类型),因为没有赋值，未发生引用变更</span><br><span class="line">print(a) # [&apos;1&apos;, 2, [1, 2, 3, 7]]</span><br><span class="line">print(b) # [&apos;1&apos;, 2, [1, 2, 3, 7]]</span><br><span class="line"></span><br><span class="line">########更改已有的名字引用,可变/不可变数据类型########</span><br><span class="line">b[2]=3  # b[2]更改后a[2]不会保持一致；---b[2]是数字(不可变类型),  因为赋值，发生了引用变更</span><br><span class="line">print(a)   # [&apos;1&apos;, 2, [1, 2, 3, 7]]</span><br><span class="line">print(b)   # [&apos;1&apos;, 2, 3]</span><br><span class="line"></span><br><span class="line">########更改未有的名字引用######################</span><br><span class="line">b.append(0)  # b添加了新的名字引用，a不会保持一致；---浅copy只能同步更改已有的名字引用</span><br><span class="line">print(a)   # [&apos;1&apos;, 2, [1, 2, 3, 7]]</span><br><span class="line">print(b)   # [&apos;1&apos;, 2, [1, 2, 3, 7], 0]</span><br></pre></td></tr></table></figure>
<h4 id="深copy"><a href="#深copy" class="headerlink" title="深copy"></a>深copy</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">from copy import deepcopy</span><br><span class="line">a=[&quot;1&quot;,2,[1,2,3]]</span><br><span class="line">c=deepcopy(a)  # 递归复制所有引用成员（而不是只复制引用）；c和a之间是独立的，没啥关系了，不会同步；</span><br></pre></td></tr></table></figure>
<h3 id="闭包"><a href="#闭包" class="headerlink" title="闭包"></a>闭包</h3><p><strong>闭包是指函数离开生成环境后，仍可记住并持续引用词法作用域的外部变量。</strong></p>
<h4 id="理论-3"><a href="#理论-3" class="headerlink" title="理论"></a>理论</h4><p>1）根据可变对象和不可变对象;<br>2）根据只有赋值的时候,才会便能引用关系;<br>3）闭包引起的环境变量叫做自由变量，保存在函数对象的<strong>closure</strong>属性里，从内存的Fast转到DEREF里；</p>
<h4 id="普通的闭包"><a href="#普通的闭包" class="headerlink" title="普通的闭包"></a>普通的闭包</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">def func():</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    方法返回了一个函数</span><br><span class="line">    函数内部需要外部的变量count</span><br><span class="line">    count成为自由变量，引用指向代码对象的__closure__</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    # count = [0]</span><br><span class="line">    count = 5  # 不可变对象</span><br><span class="line"></span><br><span class="line">    def foo():</span><br><span class="line">        # count[0] = count[0] + 1</span><br><span class="line">        num = count + 1</span><br><span class="line">        # fu()</span><br><span class="line">        print(num)</span><br><span class="line"></span><br><span class="line">    return foo</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">cc = func()</span><br><span class="line">print(cc.__closure__)  # (&lt;cell at 0x052A2290: int object at 0x5B43D470&gt;,)</span><br></pre></td></tr></table></figure>
<h4 id="记住外部状态的闭包"><a href="#记住外部状态的闭包" class="headerlink" title="记住外部状态的闭包"></a>记住外部状态的闭包</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">def func():</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    方法返回了一个函数</span><br><span class="line">    函数内部需要外部的变量count</span><br><span class="line">    count成为自由变量，引用指向代码对象的__closure__</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    count = [0]</span><br><span class="line"></span><br><span class="line">    # count = 5  # 不可变对象</span><br><span class="line"></span><br><span class="line">    def foo():</span><br><span class="line">        count[0] = count[0] + 1</span><br><span class="line">        # num = count + 1</span><br><span class="line">        # fu()</span><br><span class="line">        print(count)</span><br><span class="line"></span><br><span class="line">    return foo</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">cc = func()</span><br><span class="line">print(cc.__closure__)  # (&lt;cell at 0x052A2290: int object at 0x5B43D470&gt;,)</span><br><span class="line">cc()  # [1]</span><br><span class="line">cc()  # [2]</span><br></pre></td></tr></table></figure>
<h4 id="传递函数的闭包"><a href="#传递函数的闭包" class="headerlink" title="传递函数的闭包"></a>传递函数的闭包</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">def fu():</span><br><span class="line">    print(&quot;inner&quot;)</span><br><span class="line"></span><br><span class="line">def func(fun):</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">	传入的参数，创建fun指向它，并因为foo的调用，成为自由变量</span><br><span class="line">    方法返回了一个函数</span><br><span class="line">    函数内部需要外部的变量count</span><br><span class="line">    count成为自由变量，引用指向代码对象的__closure__</span><br><span class="line">    &apos;&apos;&apos;</span><br><span class="line">    count = [0]</span><br><span class="line"></span><br><span class="line">    # count = 5  # 不可变对象</span><br><span class="line"></span><br><span class="line">    def foo():</span><br><span class="line">        count[0] = count[0] + 1</span><br><span class="line">        # num = count + 1</span><br><span class="line">        fun()</span><br><span class="line">        print(count)</span><br><span class="line"></span><br><span class="line">    return foo</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">cc = func(fu)</span><br><span class="line">print(cc.__closure__)  # (&lt;cell at 0x052A2290: int object at 0x5B43D470&gt;,)</span><br><span class="line">cc()  # inner  [1]</span><br><span class="line">cc()  # inner  [2]</span><br></pre></td></tr></table></figure>
<p>装饰器其实就是利用了闭包的这种方式实现的。</p>
<h3 id="装饰器"><a href="#装饰器" class="headerlink" title="装饰器"></a>装饰器</h3><p>原理就是利用闭包在函数里传入一个函数对象，函数对象在闭包里调用。</p>
<h4 id="无参装饰器"><a href="#无参装饰器" class="headerlink" title="无参装饰器"></a>无参装饰器</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">def w1(func):</span><br><span class="line">    def inner():</span><br><span class="line">        # 验证1</span><br><span class="line">        # 验证2</span><br><span class="line">        # 验证3</span><br><span class="line">        return func()</span><br><span class="line">    return inner</span><br><span class="line">#方法一：</span><br><span class="line">def f1():</span><br><span class="line">    print &apos;f1&apos;</span><br><span class="line">cc=w1(f1)</span><br><span class="line">cc()</span><br><span class="line">#方法二：</span><br><span class="line">@w1</span><br><span class="line">def f1():</span><br><span class="line">    print &apos;f1&apos;</span><br><span class="line">f1()</span><br></pre></td></tr></table></figure>
<h4 id="带参装饰器"><a href="#带参装饰器" class="headerlink" title="带参装饰器"></a>带参装饰器</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">def w2(av)：</span><br><span class="line">	def w1(func):</span><br><span class="line">    	def inner():</span><br><span class="line">			# 验证1</span><br><span class="line">			# 验证2</span><br><span class="line">			# 验证3</span><br><span class="line">			print(av)</span><br><span class="line">			return func()</span><br><span class="line">    	return inner</span><br><span class="line">	return w1</span><br><span class="line"></span><br><span class="line">@w1(&apos;autor&apos;)</span><br><span class="line">def f1():</span><br><span class="line">    print &apos;f1&apos;</span><br><span class="line">f1()</span><br></pre></td></tr></table></figure>
<p>带参的装饰器，就是又加了一层嵌套</p>

      
    </div>

    

    
    
    

    <div>
          
            
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>

  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/2018/03/27/python基础回顾（一）/">python基础回顾（一）</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Q.hongtao 的个人博客">Q.hongtao</a></p>
  <p><span>发布时间:</span>2018年03月27日 - 23:03</p>
  <p><span>最后更新:</span>2018年03月28日 - 13:03</p>
  <p><span>原始链接:</span><a href="/2018/03/27/python基础回顾（一）/" title="python基础回顾（一）">http://7ht.gitee.io/2018/03/27/python基础回顾（一）/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://7ht.gitee.io/2018/03/27/python基础回顾（一）/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>
</div>
<script>
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({
          title: "",
          text: '复制成功',
          icon: "success",
          showConfirmButton: true
          });
        });
    });
</script>


          
      </div>

    

    

    
  <div>
  
    

  
</div>
    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/26/IO多路复用模块selectors/" rel="next" title="IO多路复用模块selectors">
                <i class="fa fa-chevron-left"></i> IO多路复用模块selectors
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/28/协程模块asyncio/" rel="prev" title="协程模块asyncio">
                协程模块asyncio <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/head_cat.jpg"
                alt="Q.hongtao" />
            
              <p class="site-author-name" itemprop="name">Q.hongtao</p>
              <p class="site-description motion-element" itemprop="description">没有可怕的深度 就没有美丽的水面</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">34</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">42</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/ht-dep" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:15662728521@163.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#python基础回顾"><span class="nav-number">1.</span> <span class="nav-text">python基础回顾</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#演变"><span class="nav-number">1.0.1.</span> <span class="nav-text">演变</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#理论"><span class="nav-number">1.0.2.</span> <span class="nav-text">理论</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#变量"><span class="nav-number">1.0.3.</span> <span class="nav-text">变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#类"><span class="nav-number">1.0.4.</span> <span class="nav-text">类</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#对象"><span class="nav-number">1.0.5.</span> <span class="nav-text">对象</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基础数据（对象）类型："><span class="nav-number">1.0.6.</span> <span class="nav-text">基础数据（对象）类型：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#名字空间-namespace"><span class="nav-number">1.0.7.</span> <span class="nav-text">名字空间(namespace)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#作用域"><span class="nav-number">1.0.8.</span> <span class="nav-text">作用域</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#理论-1"><span class="nav-number">1.0.8.1.</span> <span class="nav-text">理论</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#局部作用域里的变量—使用dis-dis模块反汇编查看作用域"><span class="nav-number">1.0.8.2.</span> <span class="nav-text">局部作用域里的变量—使用dis.dis模块反汇编查看作用域</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#函数的参数"><span class="nav-number">1.0.8.3.</span> <span class="nav-text">函数的参数</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#引用、浅copy、深copy"><span class="nav-number">1.0.9.</span> <span class="nav-text">引用、浅copy、深copy</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#理论-2"><span class="nav-number">1.0.9.1.</span> <span class="nav-text">理论</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#引用：指向同一个对象"><span class="nav-number">1.0.9.2.</span> <span class="nav-text">引用：指向同一个对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#浅copy：只复制对象内部的已有的名字引用"><span class="nav-number">1.0.9.3.</span> <span class="nav-text">浅copy：只复制对象内部的已有的名字引用;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#深copy"><span class="nav-number">1.0.9.4.</span> <span class="nav-text">深copy</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#闭包"><span class="nav-number">1.0.10.</span> <span class="nav-text">闭包</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#理论-3"><span class="nav-number">1.0.10.1.</span> <span class="nav-text">理论</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#普通的闭包"><span class="nav-number">1.0.10.2.</span> <span class="nav-text">普通的闭包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#记住外部状态的闭包"><span class="nav-number">1.0.10.3.</span> <span class="nav-text">记住外部状态的闭包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#传递函数的闭包"><span class="nav-number">1.0.10.4.</span> <span class="nav-text">传递函数的闭包</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#装饰器"><span class="nav-number">1.0.11.</span> <span class="nav-text">装饰器</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#无参装饰器"><span class="nav-number">1.0.11.1.</span> <span class="nav-text">无参装饰器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#带参装饰器"><span class="nav-number">1.0.11.2.</span> <span class="nav-text">带参装饰器</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ht-dep</span>

  

  
</div>



















        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.6"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.6"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.6"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.6"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.6"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.6"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.6"></script>



  



	





  





  










  





  

  

  

  

  
  

  

  

  

  


<script src="/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"display":{"position":"right","width":100,"height":150},"model":{"jsonPath":"/live2dw/assets/tororo.model.json"},"mobile":{"show":false,"scale":0.5},"react":{"opacityDefault":1,"opacityOnHover":0.2}});</script></body>
</html>
